#pragma once
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "compiler.hpp"
#include "../comm/util.hpp"

namespace ns_runner
{
    using namespace ns_until;
    class Runner
    {
    public:
        Runner()
        {
        }
        ~Runner()
        {
        }

        //添加运行的时间限制
        static void SetProcLimit(int _cpu_limit, int _mem_limit)
        {
            // 设置CPU时长
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            cpu_rlimit.rlim_cur = _cpu_limit;
            setrlimit(RLIMIT_CPU, &cpu_rlimit);

            // 设置内存大小
            struct rlimit mem_rlimit;
            mem_rlimit.rlim_max = RLIM_INFINITY;
            mem_rlimit.rlim_cur = _mem_limit * 1024; // 转化成为KB
            setrlimit(RLIMIT_AS, &mem_rlimit);
        }

        static int run(const std::string &file_name,int cpu_limit, int mem_limit)
        {
            std::string _execute = PathUtil::Exe(file_name);
            std::string _stdin = PathUtil::Stdin(file_name);
            std::string _stdout = PathUtil::Stdout(file_name);
            std::string _stderr = PathUtil::Stderr(file_name);

            umask(0);
            int _stdin_fd = open(PathUtil::Stdin(file_name).c_str(), O_CREAT | O_WRONLY, 0664);
            int _stdout_fd = open(PathUtil::Stdout(file_name).c_str(), O_CREAT | O_WRONLY, 0664);
            int _stderr_fd = open(PathUtil::Stderr(file_name).c_str(), O_CREAT | O_WRONLY, 0664);

            // 判断一下是否创建成功了
            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                ELOG("运行时,创建流失败\n");
                return -1;
            }
            pid_t pid = fork();
            if (pid < 0)
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                ELOG("创建子进程失败!\n");
                return -2;
            }
            else if (pid == 0)
            {

                // 重定向
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);


                 SetProcLimit(cpu_limit, mem_limit);
                // 接下来进行程序替换
                execl(_execute.c_str(), _execute.c_str(), nullptr /*忘记nullptr了*/);
                ELOG("程序替换失败!\n");
                exit(1);
            }

            close(_stdin_fd);
            close(_stdout_fd);
            close(_stderr_fd);
            int status = 0;
            waitpid(pid, &status, 0);
            ILOG("代码跑完了,没有被信号终止,结果:%d\n", status & 0x7f);
            return status & 0x7f;
        }

    private:
    };
}